<template>
  <div class="url-picture-upload">
    <a-input-group compact>
      <a-input
        v-model:value="fileUrl"
        style="width: calc(100% - 120px)"
        placeholder="请输入图片url"
      />
      <a-button type="primary" style="width: 120px" :loading="loading" @click="handleUpload"
        >提交</a-button
      >
    </a-input-group>
    <div class="image-wrapper">
      <img v-if="picture?.url" :src="picture?.url" alt="avatar" />
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import { uploadPictureByUrlUsingPost } from '../api/pictureController'

const fileUrl = ref<string>()

interface Props {
  picture?: API.PictureVO
  spaceId?: number
  onSuccess?: (newPicture: API.PictureVO) => void
}
const props = defineProps<Props>()
const loading = ref<boolean>(false)
/**
 * 上传图片
 * @param file
 */
const handleUpload = async () => {
  loading.value = true
  try {
    const params: API.PictureUploadDTO = { fileUrl: fileUrl.value }
    params.spaceId = props.spaceId
    if (props.picture) {
      params.id = props.picture.id
    }
    const res = await uploadPictureByUrlUsingPost(params)
    if (res.data.code === 200) {
      message.success('上传成功')
      props.onSuccess?.(res.data.data)
    } else {
      message.error('上传失败：' + res.data.data)
    }
  } catch (error) {
    message.error('上传异常')
  }
  loading.value = false
}
</script>
<style scoped>
.url-picture-upload {
  margin-bottom: 16px;
}

.url-picture-upload .image-wrapper {
  display: flex; /* 弹性布局 */
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  margin-top: 16px;
  min-height: 200px; /* 可按需要设置高度，确保能垂直居中 */
  border: 1px dashed #ccc; /* 可选：方便调试容器大小 */
}

.url-picture-upload .image-wrapper img {
  max-width: 100%;
  max-height: 480px;
  object-fit: contain; /* 保持比例缩放 */
}
</style>
